import {
  useMutation,
  UseMutationOptions,
  UseMutationResult,
} from "@tanstack/react-query";
import { useGlobalLoadingStore } from "@/lib/globalLoadingStore";
import { useGlobalErrorStore } from "@/lib/globalErrorStore";

/**
 * 通用 API Mutation hooks，支持自定义请求函数（如 authenticatedRequest），自动全局 loading/error
 */
export function useApiMutation<
  TData = unknown,
  TVariables = unknown,
  TError = Error
>(
  mutationFn: (variables: TVariables) => Promise<TData>,
  options?: UseMutationOptions<TData, TError, TVariables>
): UseMutationResult<TData, TError, TVariables> {
  const setLoading = useGlobalLoadingStore((s) => s.setLoading);
  const setError = useGlobalErrorStore((s) => s.setError);

  return useMutation<TData, TError, TVariables>({
    mutationFn: async (variables) => {
      setLoading(true);
      try {
        const result = await mutationFn(variables);
        setLoading(false);
        return result;
      } catch (err) {
        setLoading(false);
        setError(err instanceof Error ? err.message : "请求失败");
        throw err;
      }
    },
    onError: (error, ...rest) => {
      setError(error instanceof Error ? error.message : "请求失败");
      options?.onError?.(error, ...rest);
    },
    ...options,
  });
}
